#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from common.common import exter_attack, output_result_file, report_job_details
from common.common_models import SubJobDetails, LogDetail
from common.common_models import ActionResult
from common.const import ExecuteResultEnum, SubJobStatusEnum
from goldendb.handle.common.const import LogLevel
from hcs.gaussdb.common.const import EnvName, ErrorCode
from hcs.gaussdb.common.gaussdb_pydantic import ListAppV2Response
from hcs.gaussdb.common.safe_get_information import ResourceParam
from hcs.gaussdb.handle.resource.resource_info import ResourceInfo
from hcs.gaussdb.logger import log


class ResourceAbility:
    @staticmethod
    @exter_attack
    def check_application(req_id, job_id, sub_id, data):
        """
        通用接口: 检查项目连通性
        """
        log.info(f"step 1-1: start to check application.")
        check_output = ActionResult(code=ExecuteResultEnum.SUCCESS)
        EnvName.IAM_USERNAME = "appEnv_auth_authKey"
        EnvName.IAM_PASSWORD = "appEnv_auth_authPwd"
        # 组装资源接入请求体
        param_inst = ResourceParam(req_id)
        # 项目名称
        project_name = param_inst.get_project_name()
        # 项目ID
        project_id = param_inst.get_project_id()
        # 管控面地址
        project_addr = param_inst.get_api_addr()
        # 租户所属用户
        project_domain = param_inst.get_domain_account()
        # 业务面地址
        business_addr = param_inst.get_business_addr()
        fun_inst = ResourceInfo(req_id, data, project_addr, project_name, project_domain, business_addr, project_id)
        # 获取token
        ret, body, header = fun_inst.get_token_info()
        if not ret:
            log.error(f"Failed access hcs!, err body: {body}, err header: {header}")
            check_output.code = ExecuteResultEnum.INTERNAL_ERROR
            check_output.body_err = ErrorCode.ERR_RESOURCE_ABILITY.value
            check_output.message = "Check application failed!"
            output_result_file(req_id, check_output.dict(by_alias=True))
            return True
        token = header.get("X-Subject-Token", None)
        if not token:
            log.error("Failed get Token!")
            check_output.code = ExecuteResultEnum.INTERNAL_ERROR
            check_output.body_err = ErrorCode.ERR_RESOURCE_ABILITY.value
            check_output.message = "Check application failed!"
            output_result_file(req_id, check_output.dict(by_alias=True))
            return True
        output_result_file(req_id, check_output.dict(by_alias=True))
        log.info(f"step 1-1: end to check application.")
        return True

    @staticmethod
    @exter_attack
    def query_cluster(req_id, job_id, sub_id, data):
        """
        通用接口: 查询项目版本
        """
        log_detail = LogDetail(logInfo="plugin_task_subjob_success_label",
                               logLevel=LogLevel.INFO)
        report_job_details(req_id,
                           SubJobDetails(taskId=job_id, subTaskId=sub_id, progress=100, logDetail=[log_detail],
                                         taskStatus=SubJobStatusEnum.COMPLETED.value))
        return True

    @staticmethod
    @exter_attack
    def list_application_v2(req_id, job_id, sub_id, data):
        """
        通用接口: 查询实例列表
        """
        log.info(f"step 1-3: start to list application v2.")
        check_output = ActionResult(code=ExecuteResultEnum.SUCCESS)
        # 租户信息
        EnvName.IAM_USERNAME = "appEnv_auth_authKey"
        EnvName.IAM_PASSWORD = "appEnv_auth_authPwd"
        # 组装资源接入执行体
        param_inst = ResourceParam(req_id)
        # 项目名
        project_name = param_inst.get_project_name()
        # 项目Id
        project_id = param_inst.get_project_id()
        # 管控面地址
        project_addr = param_inst.get_api_addr()
        # 业务地址
        business_addr = param_inst.get_business_addr()
        # 租户所属用户
        project_domain = param_inst.get_domain_account()
        fun_inst = ResourceInfo(req_id, data, project_addr, project_name, project_domain, business_addr, project_id)
        # 查询实例列表
        try:
            resource = fun_inst.get_instance_json()
        except Exception as err:
            log.error(f"List application failed for {err.error_message}")
            check_output.code = ExecuteResultEnum.INTERNAL_ERROR
            check_output.body_err = ErrorCode.ERR_RESOURCE_ABILITY.value
            check_output.message = "List application failed!"
            output_result_file(req_id, check_output.dict(by_alias=True))
        response = ListAppV2Response()
        response.total = len(resource.get("instances", []))
        for instance in resource.get("instances", []):
            resource_info = dict()
            resource_info["type"] = "Database"
            resource_info["subType"] = "HCSGaussDBInstance"
            resource_info["name"] = instance.get("name")
            resource_info["id"] = instance.get("id")
            region = instance.get("region", "")
            version = instance.get("datastore", "").get("version", "")
            resource_info["version"] = version
            resource_info["extendInfo"] = {
                "version": version,
                'status': instance.get("status", "ABNORMAL"),
                "region": region
            }
            response.resource_list.append(resource_info)
        log.info(f"step 1-3: list_application_v2_result: {response}")
        output_result_file(req_id, response.dict(by_alias=True))
        log.info(f"step 1-3: end to list application v2.")
        return True
